package com.telpoo.bhlib.ads;

import java.util.Calendar;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.doubleclick.PublisherAdRequest;
import com.google.android.gms.ads.doubleclick.PublisherAdView;
import com.google.android.gms.ads.doubleclick.PublisherInterstitialAd;
import com.google.android.gms.ads.mediation.admob.AdMobExtras;
import com.telpoo.bhlib.BHListener;
import com.telpoo.bhlib.BHUtils;
import com.telpoo.frame.utils.Mlog;
import com.telpoo.frame.utils.RootSupport;
import com.telpoo.frame.utils.ScreenUtils;
import com.telpoo.frame.utils.Utils;

public class BHAds {
	private PublisherInterstitialAd adFull;
	private String SPR_countClick = "count click bhads";
	private String appname;
	private String appcat;
	private String adposition;
	private Activity ct;
	private ViewGroup rootadView;

	private PublisherAdView adView;
	private PublisherAdRequest adRequestAdview;
	private Runnable runnable;
	private static BHAds bhAds;
	private long lastedShowAdsFull = 0;
	BHListener listener;

	private BHAds() {

	}

	public void init(Activity ct, ViewGroup rootadView, String appname, String appcat, String adposition) {
		this.appname = appname;
		this.appcat = appcat;
		this.adposition = adposition;
		this.ct = ct;
		this.rootadView = rootadView;
	}

	public void init(Activity ct, ViewGroup rootadView, String appname, String appcat, String adposition, BHListener listener) {
		this.appname = appname;
		this.appcat = appcat;
		this.adposition = adposition;
		this.ct = ct;
		this.rootadView = rootadView;
		this.listener = listener;
	}

	public static BHAds getInstance() {
		if (bhAds == null) {
			bhAds = new BHAds();
			return bhAds;
		} else
			return bhAds;
	}

	public PublisherAdRequest getAdRequest(String appname, String appcat, String adposition, String appviews) {
		Bundle bundle = new Bundle();

		if (appname != null)
			bundle.putString("appname", appname);
		if (appcat != null)
			bundle.putString("appcat", appcat);
		if (adposition != null)
			bundle.putString("adposition", adposition);
		if (appviews != null)
			bundle.putString("appviews", appviews);

		bundle.putString("jb", "" + RootSupport.isDeviceRooted());

		AdMobExtras extras = new AdMobExtras(bundle);
		PublisherAdRequest adRequest = new PublisherAdRequest.Builder().addNetworkExtras(extras).build();

		return adRequest;
	}

	public void loadAdFull(final Context ct, String appView) {
		boolean adsState = BHUtils.getAdsState(ct);
		if (!adsState) {
			Log.i("Ads", "BHAds - loadAdFull -  ads disabled");
			return; // disabled ads
		}

		final PublisherAdRequest adRequestAdview12 = getAdRequest(appname, appcat, adposition, appView);
		lastedShowAdsFull = Calendar.getInstance().getTimeInMillis();
		Utils.saveStringSPR(SPR_countClick, "0", ct);

		if (adFull == null) {
			adFull = new PublisherInterstitialAd(ct);
			adFull.setAdUnitId("/35883025/bha_320a");
		}

		AdListener adlistener1 = new AdListener() {

			@Override
			public void onAdLoaded() {
				super.onAdLoaded();
				adFull.show();

			}

			@Override
			public void onAdClosed() {

				super.onAdClosed();

			}

			@Override
			public void onAdFailedToLoad(int errorCode) {
				super.onAdFailedToLoad(errorCode);
				// adFull.loadAd(adRequestAdview);
			}

		};

		adFull.setAdListener(adlistener1);
		adFull.loadAd(adRequestAdview12);
	}

	public void countclick_hidekeyboard(final View view, final Activity activity) {
		if (view == null)
			return;

		view.setOnTouchListener(new OnTouchListener() {
			// View mview=view;
			public boolean onTouch(View v, MotionEvent event) {

				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					String a = Utils.getStringSPR(SPR_countClick, activity);
					Mlog.T("countclick_hidekeyboard1 -" + a);
					int count1 = 0;
					try {
						count1 = Integer.parseInt(a);
					} catch (Exception e) {

					}
					count1 = count1 + 1;

					if (!(view instanceof EditText))
						if (activity != null)
							Utils.hideSoftKeyboard(activity);

					Utils.saveStringSPR(SPR_countClick, "" + count1, activity);
					/*
					 * if(count1>=30){ loadAdFull(activity);
					 * Utils.saveStringSPR(Defi.SPR.countClick, "0", activity);
					 * }
					 */
				}
				return false;
			}

		});

		// If a layout container, iterate over children and seed recursion.
		if (view instanceof ViewGroup) {

			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

				View innerView = ((ViewGroup) view).getChildAt(i);

				countclick_hidekeyboard(innerView, activity);
			}
		}
	}

	private void setupAdmob() {
		loadAdFull(ct, "99");
		countclick_hidekeyboard(((Activity) ct).getWindow().getDecorView().findViewById(android.R.id.content).getRootView(), (Activity) ct);

		adView = new PublisherAdView(ct);

		int screenWidth = ScreenUtils.getWindowsWidth(ct);
		

		int density = (int) ct.getResources().getDisplayMetrics().density;
		if (screenWidth >= density * 728) {
			adView.setAdUnitId("/35883025/bha_728a");
			adView.setAdSizes(AdSize.LEADERBOARD);
		} else {
			adView.setAdUnitId("/35883025/bha_320a");
			adView.setAdSizes(AdSize.BANNER);
		}

		adView.setVisibility(View.GONE);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
		rootadView.addView(adView, params);

		AdListener adlistener = new AdListener() {

			@Override
			public void onAdLoaded() {
				super.onAdLoaded();
				adView.setVisibility(View.VISIBLE);
			}

			@Override
			public void onAdFailedToLoad(int errorCode) {
				super.onAdFailedToLoad(errorCode);
				// adView.loadAd(adRequestAdview);
			}
		};

		adRequestAdview = getAdRequest(appname, appcat, adposition, null);
		adView.setAdListener(adlistener);
		adView.loadAd(adRequestAdview);

		final Handler handler = new Handler();
		runnable = new Runnable() {

			@Override
			public void run() {
				long curTime = Calendar.getInstance().getTimeInMillis();

				String a = Utils.getStringSPR(SPR_countClick, ct);
				// Mlog.T("countclick_hidekeyboard1 -" + a);
				int count1 = 0;
				try {
					count1 = Integer.parseInt(a);
				} catch (Exception e) {

				}

				if (count1 >= 30 && curTime - lastedShowAdsFull > 300000) {
					Mlog.T("show ads -count1=" + count1 + " -=" + (curTime - lastedShowAdsFull));
					loadAdFull(ct, "100");
				} else if (curTime - lastedShowAdsFull > 1800000) {

					Mlog.T("show ads2=" + (curTime - lastedShowAdsFull));
					loadAdFull(ct, "100");
				}

				handler.postDelayed(runnable, 60000);

			}
		};
		handler.postDelayed(runnable, 1);

	}

	public void onCreate() {
		Utils.saveStringSPR(SPR_countClick, "0", ct);
		setupAdmob();
	}

	public void onDestroy() {
		if (adView != null)
			adView.destroy();
	}

}
